package http;

import cn.hutool.core.lang.Validator;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class HttpDownload {

    /**
     * java 模拟 http 下载文件
     *
     * @param url      下载地址
     * @param savePath 保存路径
     * @param fileName 下载文件名
     * @return
     */
    public static void download(String url, String savePath, String fileName) throws IOException {

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            StringBuffer encodeUrl = new StringBuffer();
            String strs[] = url.split("/");
            int i = 0;
            for (String s : strs) {
                if (i == (strs.length - 1)) {
                    if (Validator.isChinese(s)) {
                        encodeUrl.append(URLEncoder.encode(s, "UTF-8"));
                    } else {
                        encodeUrl.append(s);
                    }
                } else {
                    if (Validator.isChinese(s)) {
                        encodeUrl.append(URLEncoder.encode(s, "UTF-8")).append("/");
                    } else {
                        encodeUrl.append(s).append("/");
                    }
                }
                i++;
            }
            URL httpUrl = new URL(encodeUrl.toString());
            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestProperty("Accept-Language", "zh-CN");
            connection.connect();
            InputStream is = connection.getInputStream();
            bis = new BufferedInputStream(is);
            File file = new File(savePath);
            if (!file.mkdirs()) {
                file.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file + File.separator + fileName);
            bos = new BufferedOutputStream(fos);
            int b;
            byte[] byArr = new byte[1024 * 4];
            while ((b = bis.read(byArr)) != -1) {
                bos.write(byArr, 0, b);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
